/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.logiclander.ricemine.utils;

import java.util.List;
import org.kuali.rice.kim.bo.entity.dto.KimDefaultableInfo;
import org.kuali.rice.kns.bo.DefaultableInactivateable;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.DirContextAdapter;

/**
 *
 * @author tcarroll
 */
public class LdapUtilities {

  public static String buildDn(DirContextAdapter context, boolean convertRdnKeysToUpperCase) {
    DistinguishedName dn = (DistinguishedName) context.getDn();
    StringBuilder dnBuilder = new StringBuilder();
    for (int i = dn.size() - 1; i >= 0; i--) {
      if (convertRdnKeysToUpperCase) {
        dnBuilder.append(dn.getLdapRdn(i).getKey().toUpperCase());
      } else {
        dnBuilder.append(dn.getLdapRdn(i).getKey());
      }
      dnBuilder.append('=').append(dn.getLdapRdn(i).getValue());
      if (i != 0) {
        dnBuilder.append(',');
      }
    }
    return dnBuilder.toString();
  }

  public static String buildGuid(DirContextAdapter context) {
    byte[] byteGUID = (byte[]) context.getObjectAttribute("objectGUID");
    String stringGUID = "";
    for (int i = 0; i < byteGUID.length; i++) {
      stringGUID = stringGUID + "\\" + AddLeadingZero((int) byteGUID[i] & 0xFF);
    }
    return stringGUID;
  }

  private static String AddLeadingZero(int k) {
    return (k < 0xF) ? "0" + Integer.toHexString(k) : Integer.toHexString(k);
  }

  public static String materialize(String str) {
    return materialize(str,null);
  }

  public static String materialize(String str, String dflt) {
    if(dflt==null) {
      dflt="";
    }
    if(str==null) {
      return dflt;
    }
    return str;
  }

	public static DefaultableInactivateable getDefaultItem( List<? extends DefaultableInactivateable> list ) {
		// find the default entry
		for ( DefaultableInactivateable item : list ) {
			if ( item.isDefault() && item.isActive() ) {
				return item;
			}
		}
		// if no default, return the first
		if ( list.size() > 0 ) {
			return list.get( 0 );
		}
		// if neither, return null
		return null;
	}

  public static KimDefaultableInfo getKimDefaultItem( List<? extends KimDefaultableInfo> list ) {
		// find the default entry
		for ( KimDefaultableInfo item : list ) {
			if ( item.isDefault() && item.isActive() ) {
				return item;
			}
		}
		// if no default, return the first
		if ( list.size() > 0 ) {
			return list.get( 0 );
		}
		// if neither, return null
		return null;
	}
}
